﻿using System;
using System.Linq;
using UniMana.Utils.Data;
using DevExpress.XtraBars;
using UniMana.Data;
using System.Data;
using UniMana.Utils.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors;
using UniMana.Utils.Helper;


namespace UniMana.Win.Training
{
    public partial class FrmTrainingProgram_SubDetail : DevExpress.XtraEditors.XtraForm
    {

        private DBMain m_data = new DBMain();
        private DataTable m_tbRight = new DataTable();//Danh sách phải
        private DataTable m_tbLeft = new DataTable(); //Danh sách trái

        private string m_Rule = UniMana.Utils.Configs.RuleConfig.TRAININGPRO;
        public Training_TrainingProgramInfo proInfo = new Training_TrainingProgramInfo();
        

        public FrmTrainingProgram_SubDetail()
        {
            if (!SysUtils.CheckAccessByRule(m_Rule))
            {
                return;
            }
            InitializeComponent();
            SysUtils.SetRuleControl(this.Controls, this.Name);
            LoadData();
            xtcProgramDetail.SelectedTabPage = xtpProgram;

        }

        private void FrmTrainingProgram_Detail_Load(object sender, EventArgs e)
        { 
            
            loadDataToGrid(this.proInfo.Properties.Training_TrainingProgramKey);
            TabShowFrm.ShowTabbedMdi(new FrmTrainingProgram_SubSchedule((int)this.proInfo.Properties.Training_TrainingProgramKey), xtcProgramDetail);
            xtcProgramDetail.SelectedTabPage = xtpProgram;

            bsiName.Caption = "Tên chương trình đào tạo: " + this.proInfo.Properties.Name;
            bsiTotalCredit.Caption = "Tổng số tín chỉ: " + this.proInfo.Properties.TotalCredits.ToString();
        }

        public void loadDataToGrid(int proKey)
        {
            lcgTrainingProgram.LoadOneRecord(proInfo.m_bds);

            #region [Get data]
            var left = from sbj in m_data.m_DCReadOnly.Training_Subjects
                         where !(from trnDtl in m_data.m_DCReadOnly.Training_TrainingProgram_Details
                                 where trnDtl.Training_TrainingProgramKey == proKey
                                 select trnDtl.Training_SubjectKey).Contains(sbj.Training_SubjectKey)
                         select new 
                         { 
                             sbj.Training_SubjectKey,
                             sbj.ID,
                             sbj.Name,
                             sbj.Catalogue_DepartmentKey,
                             sbj.DateCreate,
                             Credits = sbj.Credits1 + sbj.Credits2 + sbj.Credits3 + sbj.Credits4,
                             sbj.Credits1,
                             sbj.Credits2,
                             sbj.Credits3,
                             sbj.Credits4
                             
                         };
            gctLeft.DataSource = left.ToDataTable();


            var right = from trn in m_data.m_DCReadOnly.Training_TrainingProgram_Details
                        join sbj in m_data.m_DCReadOnly.Training_Subjects on trn.Training_SubjectKey equals sbj.Training_SubjectKey
                        join trngourp in m_data.m_DCReadOnly.Training_SubjectGroups on trn.Training_SubjectGroupKey equals trngourp.Training_SubjectGroupKey
                        where trn.Training_TrainingProgramKey == proKey
                        orderby trngourp.ParentKey descending
                        select new
                        {
                            sbj.Training_SubjectKey,
                            sbj.ID,
                            sbj.Name,
                            sbj.Catalogue_DepartmentKey,
                            trn.Catalogue_SubjectTypeKey,
                            trn.Training_SubjectGroupKey,
                            Credits =  sbj.Credits1 + sbj.Credits2 + sbj.Credits3 + sbj.Credits4,
                            trngourp.ParentKey,
                            trngourp.OrderID,
                            sbj.Credits1,
                            sbj.Credits2,
                            sbj.Credits3,
                            sbj.Credits4
                            //CreditsText = sbj.Credits1.ToString().Substring(0,3)
                            //CreditsText = "(" + sbj.Credits1.ToString().Substring(0, 3) + "," + sbj.Credits2.ToString().Substring(0, 3) + "," + sbj.Credits3.ToString().Substring(0, 3) + ")"
                        };
            #endregion

            if (right.Count() == 0)
            {
                DataTable tbl = new DataTable();
                DataColumn cl1 = new DataColumn("Training_SubjectKey");
                DataColumn cl2 = new DataColumn("ID");
                DataColumn cl3 = new DataColumn("Name");
                DataColumn cl4 = new DataColumn("Catalogue_SubjectTypeKey");
                DataColumn cl5 = new DataColumn("Training_SubjectGroupKey");
                DataColumn cl6 = new DataColumn("Catalogue_DepartmentKey");
                DataColumn cl7 = new DataColumn("Credits");
                DataColumn cl8 = new DataColumn("ParentKey");
                DataColumn cl9 = new DataColumn("OrderID");
                DataColumn cl10 = new DataColumn("Credits1");
                DataColumn cl11 = new DataColumn("Credits2");
                DataColumn cl12 = new DataColumn("Credits3");
                DataColumn cl13 = new DataColumn("Credits4");
                tbl.Columns.AddRange(new DataColumn[] { cl1, cl2, cl3, cl4, cl5, cl6, cl7, cl8, cl9,cl10,cl11,cl12,cl13});
                gctRight.DataSource = tbl;
            }
            else
            {
                gctRight.DataSource = right.ToDataTable();
            }

            var knlege = from sgr in m_data.m_DCReadOnly.Training_SubjectGroups
                         join knl in m_data.m_DCReadOnly.Training_TrainingPrograme_Knowleges on sgr.Training_SubjectGroupKey equals knl.Training_SubjectGroupKey
                         into grp
                         //join sty in m_data.m_DCReadOnly.Catalogue_SubjectTypes on knl.Catalogue_SubjectTypeKey equals sty.Catalogue_SubjectTypeKey
                         from j in grp.DefaultIfEmpty()
                         where j.Traning_TrainingProgrameKey == proKey
                         //where sgr.ParentKey!=0
                         select new
                         {
                             GroupKey = j.Training_SubjectGroupKey,
                             //TypeKey = sty.Catalogue_SubjectTypeKey, 
                             j.Credits
                         };
            if (knlege.Count() != 0)
            {
                gctKnowlege.DataSource = knlege.ToDataTable();
               
            }
            else
            {
                DataTable tbl = new DataTable();
                DataColumn cl1 = new DataColumn("GroupKey");
                DataColumn cl2 = new DataColumn("TypeKey");
                DataColumn cl3 = new DataColumn("Credits");
                tbl.Columns.AddRange(new DataColumn[] { cl1, cl2, cl3 });

                var knlege2 = m_data.m_DCReadOnly.Training_SubjectGroups;
                var sbjType = m_data.m_DCReadOnly.Catalogue_SubjectTypes;
                foreach (var item in knlege2)
                {
                    //foreach (var sitem in sbjType)
                    //{
                        DataRow newRow = tbl.NewRow();
                        newRow["GroupKey"] = item.Training_SubjectGroupKey;
                        //newRow["TypeKey"] = sitem.Catalogue_SubjectTypeKey; //đã bỏ ngày 01-12-2012 theo yêu cầu của Thảo
                        newRow["Credits"] = 0;
                        tbl.Rows.Add(newRow);
                    //}
                }
                gctKnowlege.DataSource = tbl;

            }
            grv.ExpandAllGroups();
                         
        }

        public void LoadData()
        {
            #region [Drop-down]
            lueCatalogue_Level.GetData(m_data.m_DCReadOnly.Catalogue_Levels);
            lueCatalogue_TrainingType.GetData(m_data.m_DCReadOnly.Catalogue_TrainingTypes);
            gluCatalogue_Major.GetData(m_data.m_DCReadOnly.Catalogue_Majors);
            lueCatalogue_Course.GetData(m_data.m_DCReadOnly.Catalogue_Courses);
            rluCatalogue_Department.GetData(m_data.m_DCReadOnly.Catalogue_Departments);

            rluCatalogue_DepartmentLeft1.GetData(m_data.m_DCReadOnly.Catalogue_Departments, "Catalogue_DepartmentKey");


            lueCatalogue_SubjectType.GetData(m_data.m_DCReadOnly.Catalogue_SubjectTypes);
            lueTraining_SubjectGroup.GetData(m_data.m_DCReadOnly.Training_SubjectGroups.Where(p => p.ParentKey != 0));

            rluCatalogue_SubjectType.GetData(m_data.m_DCReadOnly.Catalogue_SubjectTypes);
            rluTraining_SubjectGroup.GetData(m_data.m_DCReadOnly.Training_SubjectGroups); 

            rluTraining_SubjectGroupParent.GetData(m_data.m_DCReadOnly.Training_SubjectGroups,"Training_SubjectGroupKey");

            #endregion

            #region [Add Subject to Training Program Tab Page]
            rluCatalogue_DepartmentLeft.GetData(m_data.m_DCReadOnly.Catalogue_Departments, "Catalogue_DepartmentKey");
            rluCatalogue_DepartmentRight.GetData(m_data.m_DCReadOnly.Catalogue_Departments, "Catalogue_DepartmentKey");
            #endregion

            rluTraining_CatalogueSubjectType_1.GetData(m_data.m_DCReadOnly.Catalogue_SubjectTypes, "Catalogue_SubjectTypeKey", "Name");
            rluTraning_SubjectGroup_1.GetData(m_data.m_DCReadOnly.Training_SubjectGroups, "Training_SubjectGroupKey", "Name");

            
        }

        #region [xucBar-Events]
        /// <summary>
        /// Nút Save được click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {

            if (!SysUtils.CheckSaveByRule(this.m_Rule))
            {
                return;
            }
            this.Save();  //Lưu
            this.Close(); //Đóng
        }

        private void btnNew_SaveClick(object sender, ItemClickEventArgs e)
        {

            if (!SysUtils.CheckSaveByRule(this.m_Rule))
            {
                return;
            }
            this.Save();
            this.proInfo = new Training_TrainingProgramInfo();
            proInfo.m_bds.EndEdit();
            this.loadDataToGrid(proInfo.Properties.Training_TrainingProgramKey);
        }


        /// <summary>
        /// Lưu
        /// </summary>
        public void Save()
        {
            this.Validate();

            DataTable tblRight = new DataTable();
            tblRight = gctRight.DataSource as DataTable;

            //Save thiết kế chương trình đào tạo
            proInfo.Save();
            grvSubjectRight.ActiveFilterEnabled = false; //Tắt filter trước khi lưu

            for (int i = 0; i < tblRight.Rows.Count; i++)
            {
                int subjectKey = int.Parse(tblRight.Rows[i]["Training_SubjectKey"].ToString());
                Training_TrainingProgram_DetailInfo info = new Training_TrainingProgram_DetailInfo(this.proInfo.Properties.Training_TrainingProgramKey, subjectKey);
                info.Properties.Catalogue_SubjectTypeKey = int.Parse(tblRight.Rows[i]["Catalogue_SubjectTypeKey"].ToString());
                info.Properties.Training_SubjectGroupKey = int.Parse(tblRight.Rows[i]["Training_SubjectGroupKey"].ToString());
                info.Save();
            }

            //Save phân bổ kiến thức
            DataTable tblKnl = new DataTable();
            tblKnl = gctKnowlege.DataSource as DataTable;

            for (int i = 0; i < tblKnl.Rows.Count; i++)
            {
                int groupKey = int.Parse(tblKnl.Rows[i]["GroupKey"].ToString());
                //int typeKey = int.Parse(tblKnl.Rows[i]["TypeKey"].ToString()); //Bỏ ngày 01-12-2012
                Training_TrainingProgram_KnownlegeInfo info = new Training_TrainingProgram_KnownlegeInfo(this.proInfo.Properties.Training_TrainingProgramKey, groupKey /*, typeKey*/);
                info.Properties.Credits = float.Parse(tblKnl.Rows[i]["Credits"].ToString());
                info.Save();
            }


            //Xóa những dòng có trong DB nhưng không có trong datasource phải
            var existsList = m_data.m_DCSave.Training_Subjects.GetListInTrainingProgram
                                            (
                                                m_data.m_DCSave.Training_TrainingProgram_Details,
                                                this.proInfo.Properties.Training_TrainingProgramKey
                                            );


            foreach (var item in existsList)
            {
                Training_Subject sbj = item as Training_Subject;


                if (!CheckForDelete(sbj.Training_SubjectKey, tblRight))
                {
                    Training_TrainingProgram_DetailInfo info = new Training_TrainingProgram_DetailInfo(this.proInfo.Properties.Training_TrainingProgramKey, sbj.Training_SubjectKey);
                    info.Delete();
                    info.Save();
                }
            }
        }

        #endregion

        #region [Events]

        private void btnAdd_Click(object sender, EventArgs e)
        {
            MoveItems(gctRight, grvSubjectLeft,true);
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            MoveItems(gctLeft, grvSubjectRight);
        }

        #endregion

        #region [Utils]

        /// <summary>
        /// Di chuyển các ô qua lại giữa các lưới
        /// </summary>
        /// <param name="_grcTarget">GridControl đích</param>
        /// <param name="_grvSource">GridView nguồn</param>
        public void MoveItems(GridControl _grcTarget, DevExpress.XtraGrid.Views.Grid.GridView _grvSource, bool isCheck=false)
        {
            if (isCheck == true)
            {
                if (lueCatalogue_SubjectType.GetIntValue() == -1 && lueTraining_SubjectGroup.GetIntValue() == -1)
                {
                    XtraMessageBox.Show("Chưa chọn Nhóm môn/Loại môn", "Lỗi");
                    return;
                }
            }
            DataTable tbl = _grcTarget.DataSource as DataTable;
            foreach (int i in _grvSource.GetSelectedRows())
            {
                try
                {
                    DataRow newRow = tbl.NewRow();
                    newRow["Training_SubjectKey"] = _grvSource.GetRowCellValue(i, "Training_SubjectKey");
                    newRow["ID"] = _grvSource.GetRowCellValue(i, "ID");
                    newRow["Name"] = _grvSource.GetRowCellValue(i, "Name");
                    newRow["Catalogue_DepartmentKey"] = _grvSource.GetRowCellValue(i, "Catalogue_DepartmentKey");
                    if (isCheck == true) //Dạng chuyển từ lưới trái sang lưới phải
                    {
                        newRow["Catalogue_SubjectTypeKey"] = lueCatalogue_SubjectType.GetIntValue();
                        newRow["Training_SubjectGroupKey"] = lueTraining_SubjectGroup.GetIntValue();
                        newRow["ParentKey"] = m_data.m_DCReadOnly.Training_SubjectGroups.Where(p => p.Training_SubjectGroupKey == lueTraining_SubjectGroup.GetIntValue())
                                                                                              .FirstOrDefault().ParentKey;
                    }
                    newRow["Credits"] = _grvSource.GetRowCellValue(i, "Credits");
                    newRow["Credits1"] = _grvSource.GetRowCellValue(i, "Credits1");
                    newRow["Credits2"] = _grvSource.GetRowCellValue(i, "Credits2");
                    newRow["Credits3"] = _grvSource.GetRowCellValue(i, "Credits3");
                    newRow["Credits4"] = _grvSource.GetRowCellValue(i, "Credits4");

                    tbl.Rows.Add(newRow);
                }
                catch { }
            }
            _grvSource.DeleteSelectedRows();
        }

        /// <summary>
        /// Kiếm tra xóa
        /// </summary>
        /// <param name="subjectKey"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        private bool CheckForDelete(int subjectKey, DataTable source)
        {
            for (int i = 0; i < source.Rows.Count; i++)
            {
                if (int.Parse(source.Rows[i]["Training_SubjectKey"].ToString()) == subjectKey)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
    }
}